package com.bw.gmall.realtime.app.zyjdim;

import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.app.func.TableProcessFunction;
import com.bw.gmall.realtime.bean.TableProcess;
import com.bw.gmall.realtime.utils.MyKafkaUtil;
import com.bw.gmall.realtime.utils.MyPhoenixSink;
import com.bw.gmall.realtime.utils.MysqlUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class DimAppZyj {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> ds = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer("topic_db", "dimapp"));
//        ds.print();
        SingleOutputStreamOperator<JSONObject> filiterJSONDS = ds.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSONObject.parseObject(value);
                    String type = jsonObject.getString("type");
                    if (type.equals("insert") || type.equals("update") || type.equals("bootstrap-insert")) {
                        out.collect(jsonObject);
                    }
                } catch (Exception e) {
                    System.out.println("数据格式错误" + value);
                }
            }
        });
//        filiterJSONDS.print("合格");
        DataStream<String> mysqlDS = MysqlUtil.cdcMysql(env, "gmall_config", "table_process");
//        mysqlDS.print("mysql");
        MapStateDescriptor<String, TableProcess> mapstate = new MapStateDescriptor<>("mapstate", String.class, TableProcess.class);
        BroadcastStream<String> broadcastStream = mysqlDS.broadcast(mapstate);
        BroadcastConnectedStream<JSONObject, String> connect = filiterJSONDS.connect(broadcastStream);
        SingleOutputStreamOperator<JSONObject> dimDs = connect.process(new TableProcessFunction(mapstate));
        dimDs.print("最终结果");
        dimDs.addSink(new MyPhoenixSink());
        env.execute();
    }
}
